-
Notifications
You must be signed in to change notification settings - Fork 912
/
Copy pathcreate_draft_with_attachment.py
118 lines (96 loc) · 3.61 KB
/
create_draft_with_attachment.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
"""Copyright 2019 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
# [START gmail_create_draft_with_attachment]
import base64
import mimetypes
import os
from email.message import EmailMessage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
def gmail_create_draft_with_attachment():
"""Create and insert a draft email with attachment.
Print the returned draft's message and id.
Returns: Draft object, including draft id and message meta data.
Load pre-authorized user credentials from the environment.
TODO(developer) - See https://developers.google.com/identity
for guides on implementing OAuth2 for the application.
"""
creds, _ = google.auth.default()
try:
# create gmail api client
service = build("gmail", "v1", credentials=creds)
mime_message = EmailMessage()
# headers
mime_message["To"] = "[email protected]"
mime_message["From"] = "[email protected]"
mime_message["Subject"] = "sample with attachment"
# text
mime_message.set_content(
"Hi, this is automated mail with attachment.Please do not reply."
)
# attachment
attachment_filename = "photo.jpg"
# guessing the MIME type
type_subtype, _ = mimetypes.guess_type(attachment_filename)
maintype, subtype = type_subtype.split("/")
with open(attachment_filename, "rb") as fp:
attachment_data = fp.read()
mime_message.add_attachment(attachment_data, maintype, subtype)
encoded_message = base64.urlsafe_b64encode(mime_message.as_bytes()).decode()
create_draft_request_body = {"message": {"raw": encoded_message}}
# pylint: disable=E1101
draft = (
service.users()
.drafts()
.create(userId="me", body=create_draft_request_body)
.execute()
)
print(f'Draft id: {draft["id"]}\nDraft message: {draft["message"]}')
except HttpError as error:
print(f"An error occurred: {error}")
draft = None
return draft
def build_file_part(file):
"""Creates a MIME part for a file.
Args:
file: The path to the file to be attached.
Returns:
A MIME part that can be attached to a message.
"""
content_type, encoding = mimetypes.guess_type(file)
if content_type is None or encoding is not None:
content_type = "application/octet-stream"
main_type, sub_type = content_type.split("/", 1)
if main_type == "text":
with open(file, "rb"):
msg = MIMEText("r", _subtype=sub_type)
elif main_type == "image":
with open(file, "rb"):
msg = MIMEImage("r", _subtype=sub_type)
elif main_type == "audio":
with open(file, "rb"):
msg = MIMEAudio("r", _subtype=sub_type)
else:
with open(file, "rb"):
msg = MIMEBase(main_type, sub_type)
msg.set_payload(file.read())
filename = os.path.basename(file)
msg.add_header("Content-Disposition", "attachment", filename=filename)
return msg
if __name__ == "__main__":
gmail_create_draft_with_attachment()
# [END gmail_create_draft_with_attachment]